package com.yxw.sharedpreferencesdemo01;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editUsername, editPassword;
    CheckBox chk;
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//        SharedPreferences pref = getSharedPreferences("myPref", MODE_PRIVATE);
//        SharedPreferences.Editor editor = pref.edit();
//        editor.putString("name", "张三");
//        editor.putInt("age", 30);
//        editor.putLong("time", System.currentTimeMillis());
//        editor.putBoolean("default", true);
//        editor.commit();
//        editor.remove("default");
//        editor.commit();
//
//        System.out.println(pref.getString("name", ""));
//        System.out.println(pref.getInt("age", 0));

        editUsername = findViewById(R.id.editUsername);
        editPassword = findViewById(R.id.editPassword);
        chk = findViewById(R.id.chk);
        pref = getSharedPreferences("UserInfo", MODE_PRIVATE);
        pref.edit();

        String name=pref.getString("userName","");
        if(name==null){
            chk.setChecked(false);
        }else{
            chk.setChecked(true);
            editUsername.setText(name);
        }

    }

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                String name = editUsername.getText().toString().trim();
                String password = editPassword.getText().toString().trim();
                if ("amdin".equals(name) && "123345".equals(password)) {
                    if (chk.isChecked()) {
                        editor.putString("userName", name);
                        editor.commit();
                        Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
                    }else{
                        editor.remove("userName");
                        editor.commit();

                    }
                }else{
                    Toast.makeText(MainActivity.this, "禁止登陆", Toast.LENGTH_LONG).show();
                }
        }
    }
}
